package com.augurit.gzcgwsp.qyzz.qx.web;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.jbpm.api.ProcessEngine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springside.modules.orm.Page;
import org.springside.modules.web.struts2.Struts2Utils;
import com.augurit.common.base.action.BaseAction;
import com.augurit.common.base.action.CrudActionSupport;
import com.augurit.common.syscode.service.ISysCodeService;
import com.augurit.common.syscode.web.form.SysCodeForm;
import com.augurit.common.system.util.WebContextUtils;
import com.augurit.common.system.web.auth.form.LoginUserForm;
import com.augurit.common.util.lang.StringUtils;
import com.augurit.gzcgwsp.commonex.util.lang.DateUtilsEX;
import com.augurit.gzcgwsp.excelimportexport.service.IYwRqQyjyzzImportservice;
import com.augurit.gzcgwsp.printDoc.service.IYwPrintDocService;
import com.augurit.gzcgwsp.printDoc.web.form.YwPrintDocForm;
import com.augurit.gzcgwsp.qyzz.entity.YwRqQyzzAzWxRyZs;
import com.augurit.gzcgwsp.qyzz.entity.YwRqQyzzFinalAzWxRyZs;
import com.augurit.gzcgwsp.qyzz.entity.YwRqQyzzFinalJsRy;
import com.augurit.gzcgwsp.qyzz.entity.YwRqQyzzInfo;
import com.augurit.gzcgwsp.qyzz.entity.YwRqQyzzJsRy;
import com.augurit.gzcgwsp.qyzz.entity.YwRqRyzzEquipment;
import com.augurit.gzcgwsp.qyzz.entity.YwRqRyzzFinalEquipment;
import com.augurit.gzcgwsp.qyzz.entity.YwRqRyzzFinalOtherEvidence;
import com.augurit.gzcgwsp.qyzz.entity.YwRqRyzzOtherEvidence;
import com.augurit.gzcgwsp.qyzz.qx.service.IYwRqQyzzInfoQxService;
import com.augurit.gzcgwsp.qyzz.service.IYwRqQyzzEquipmentService;
import com.augurit.gzcgwsp.qyzz.web.form.YwRqQyzzInfoForm;
import com.augurit.gzcgwsp.wfex.app.doc.IOaDocCodeServiceEX;
import com.augurit.gzcgwsp.wfex.bi.service.IWfBusTemplateServiceEX;
import com.augurit.gzcgwsp.wfex.bi.service.IWfTemplateAttachmentRefServiceEX;
import com.augurit.gzcgwsp.wfex.bi.web.form.WfTemplateAttachmentRefFormEX;
import com.augurit.gzcgwsp.wfex.common.service.IWfServiceEX;
import com.augurit.gzcgwsp.wfex.common.util.WfUtilsEX;
import com.augurit.gzcgwsp.ywcmn.entity.YwComFinalQyxx;
import com.augurit.gzcgwsp.ywcmn.service.IYwComQyxxService;
import com.augurit.gzcgwsp.ywcmn.web.form.YwComQyxxForm;
import com.augurit.wf.bi.web.form.WfBusInstanceTaskForm;
import com.augurit.wf.bi.web.form.WfBusTemplateForm;
import com.augurit.wf.common.constant.WfConstant;
import com.augurit.wf.common.entity.Jbpm4HistTask;
import com.augurit.wf.common.form.WfBusSaveResult;
import com.augurit.wf.common.service.IWfBusClientService;
import com.augurit.wf.common.service.IWfService;
import com.augurit.wf.common.util.WfUtils;
import com.augurit.wf.common.web.WfBusClientAction;
import com.google.gson.Gson;

@SuppressWarnings("serial")
@Results({
    @Result(name = CrudActionSupport.RELOAD, location = "yw-rq-installentinfo.action", type = "redirect"),
    @Result(name = CrudActionSupport.SUCCESS, location = "/gzcgwsp/qyzz/YwRqQyzzInfo/YwRqQyzzInfo.jsp"),
    @Result(name = WfConstant.PRINT, location = WfConstant.PRINT_JSP),
    @Result(name = "preViewZzzs", location = "/gzcgwsp/qyzz/YwRqQyzzInfo/preViewZzzs.jsp"),
	@Result(name = "printZzzs", location = "/gzcgwsp/qyzz/YwRqQyzzInfo/printZzzs.jsp"),
	@Result(name = "preViewZzzsfb", location = "/gzcgwsp/qyzz/YwRqQyzzInfo/preViewZzzsfb.jsp"),
	@Result(name = "printZzzsfb", location = "/gzcgwsp/qyzz/YwRqQyzzInfo/printZzzsfb.jsp"),
    @Result(name = CrudActionSupport.INPUT, location = "/gzcgwsp/qyzz/YwRqQyzzInfo/qx/YwRqQyzzInfoQx-input.jsp"),
    @Result(name = WfConstant.PRINT_DIR, location = WfConstant.PRINT_DIR_JSP),
    @Result(name = "showview", location = "/gzcgwsp/qyzz/YwRqQyzzInfo/view/YwRqQyzzInfo-view.jsp"),
    @Result(name = "printJyxkfbzs", location = "/gzcgwsp/wfex/client/wf-printExcelEx.jsp"),
    @Result(name = WfConstant.MAKE_DOCUMENT, location = "/gzcgwsp/wfex/client/common/qumake-noline-document.jsp")
})
public class YwRqQyzzInfoQxAction extends WfBusClientAction<YwRqQyzzInfoForm> {
    private static final Logger log=Logger.getLogger(YwRqQyzzInfoQxAction.class);
	@Autowired
	private IYwRqQyjyzzImportservice ywRqQyjyzzImportservice; 
    @Autowired
    private IWfService wfService;
    @Autowired
    private IWfServiceEX wfServiceEX;
	@Autowired
    private IOaDocCodeServiceEX oaDocCodeServiceEX;
    @Autowired
    private IYwComQyxxService qyxxService;
    @Autowired
    private IYwRqQyzzInfoQxService ywRqQyzzInfoQxService;
    @Autowired
    private IWfBusTemplateServiceEX wfBusTemplateServiceEX;
    @Autowired
    private ProcessEngine processEngine;
    @Autowired
    private ISysCodeService syscodeService;
    @Autowired
    private IYwComQyxxService ywComQyxxService;
    @Autowired
    private IWfTemplateAttachmentRefServiceEX wfTemplateAttachmentRefServiceEX;
	@Autowired
	private IYwRqQyzzEquipmentService ywRqQyzzEquipmentService;
    @Autowired
	private IYwPrintDocService ywPrintDocService;
    private YwRqQyzzInfoForm form;
    private YwComQyxxForm qyxx;
    private Long[] checkedIds;
    private Page<YwRqQyzzInfoForm> page = new Page<YwRqQyzzInfoForm>(10);
    private SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    /**
     * 保存业务并关联流程实例
     */
    public String wfBusSave(){
    	try{
        if(form.getQyid() == null) {
            YwComQyxxForm qyxxForm = qyxxService.getFormBySqdw(form.getSqdw(),form.getTemplateCode());
            if (qyxxForm != null) {
                WfUtils.renderWfFailtureJson("该企业名称已经存在，请点击选择企业从企业列表中选择该企业！");
                return null;
            }
        }
        String isYsl = super.getParameter("isYsl");
        LoginUserForm user = (LoginUserForm)getSession().getAttribute(WebContextUtils.SES_LOGIN_USER);
        String orgName = user.getOrg().getOrgName();
		if(StringUtils.isNotBlank(orgName)){//把所属区保存到WfBusInstance表的busMemo2字段里面
			form.setSsq(orgName.substring(0,3));	
		}
        WfBusInstanceTaskForm task = this.wfBusSave((IWfBusClientService)ywRqQyzzInfoQxService, form, YwRqQyzzInfo.class.getSimpleName());
        String durationExpression = wfServiceEX.getProcDueExpressIonByTaskInstDbid(task.getTaskInstDbid());
        if (form.getDfsj() == null) {
            Date dfsj = wfServiceEX.calculateDueDate(form.getLarq(), durationExpression); 
            form.setDfsj(dfsj);
            this.save();
        }
        
        if (StringUtils.isNotBlank(isYsl) && "1".equals(isYsl)) {
//            processEngine.getExecutionService().jumpToActivity(task.getExecutionId(), "cksa");
        	String executionId =  processEngine.getHistoryService().createHistoryTaskQuery().taskId(task.getTaskInstDbid().toString()).uniqueResult().getExecutionId();
            processEngine.getExecutionService().jumpToActivity(executionId, "cksa");
            form.setYsl(null);
            ywRqQyzzInfoQxService.changeYslState(form.getId(), 2l,"");
        }
        WfUtils.renderWfBusSaveJson(task, form);
    	}catch (Exception e) {
    		WfUtils.renderWfFailtureJson("请检查输入内容长度是否过大!");
		}
        return null;
    }
    public String wfBusYslTuih() throws Exception {

    	try {
    		ywRqQyzzInfoQxService.wfBusYslTuih(form, this.getLoginUser());
			WfBusSaveResult result = new WfBusSaveResult(true, null);
			result.setTask(new WfBusInstanceTaskForm());
			Struts2Utils.renderJson(result);
		} catch (RuntimeException e) {
			WfUtils.renderWfFailtureJson("操作失败!");
			e.printStackTrace();
		}
        return null;
    }
    
    /**
	 * 套打资质证书
	 * @return
	 */
	public String preViewZzzs(){
		qyxx = ywComQyxxService.get(form.getQyid());
		//初始化打印时间
        Date da = new Date();
        Calendar cal = Calendar.getInstance();
        cal.setTime(da);
        if(qyxx.getYear() == null){
            qyxx.setYear(DateUtilsEX.convertNumber2Chinese(cal.get(Calendar.YEAR)));
        }
        if(qyxx.getMonth() == null){
            qyxx.setMonth(DateUtilsEX.convertNumber2Chinese(cal.get(Calendar.MONTH)+1));
        }
        if(qyxx.getDay() == null){
            try {
                qyxx.setDay(DateUtilsEX.convertNumber2ChineseByDay(cal.get(Calendar.DATE)));
            } catch (Exception e) {
                log.error("企业资质设置时间-天错误"+e);
            }
        }
        if(StringUtils.isBlank(qyxx.getZsbh())){
            ywRqQyzzInfoQxService.createZsbh(form);
        }
        String hjmc=getRequest().getParameter("hjmc");
        getRequest().setAttribute("hjmc", hjmc);
		return "preViewZzzs";
	}
	/**
	 * 套打资质证书
	 * @return
	 */
	public String printZzzs(){
		qyxx.setSqdw(form.getSqdw());
		ywRqQyzzInfoQxService.save(form);
		ywComQyxxService.save(qyxx);
		return "printZzzs";
	}
	/**
     * 控件套打资质证书副本
     * @return
     */
	public String printnewZzzsfb(){
	    qyxx = ywComQyxxService.get(form.getQyid());
	    String fbnum=getRequest().getParameter("fbnum");
	    if(StringUtils.isNotBlank(fbnum)){//因副本有6个编号 所以打印时候可输入
	    	form.setFbzsbh(fbnum);
	    }
        //初始化打印时间
        Date da = new Date();
        Calendar cal = Calendar.getInstance();
        cal.setTime(da);
        if(qyxx.getYear() == null){
            qyxx.setYear(DateUtilsEX.convertNumber2Chinese(cal.get(Calendar.YEAR)));
        }
        if(qyxx.getMonth() == null){
            qyxx.setMonth(DateUtilsEX.convertNumber2Chinese(cal.get(Calendar.MONTH)+1));
        }
        if(qyxx.getDay() == null){
            qyxx.setDay(DateUtilsEX.convertNumber2ChineseByDay(cal.get(Calendar.DATE)));
        }
        
        String tempPath="Templates/rqjyxk/qyzzfb.xls";
        logger.info("打印企业资质的文件路径"+tempPath);
       String context=getRequest().getSession().getServletContext().getRealPath("");
       tempPath=this.ywRqQyzzInfoQxService.writeFbData(form,qyxx,context);
       
       getRequest().setAttribute("templateFilePath",tempPath);
       logger.info("返回企业资质文件路径"+tempPath);
        return "printJyxkfbzs";
	}
	  /**
     * 控件方式套打资质证书
     * @return
     */
    public String printnewZzzs(){
        qyxx = ywComQyxxService.get(form.getQyid());
        //初始化打印时间
        Date da = new Date();
        Calendar cal = Calendar.getInstance();
        cal.setTime(da);
        if(qyxx.getYear() == null){
            qyxx.setYear(DateUtilsEX.convertNumber2Chinese(cal.get(Calendar.YEAR)));
        }
        if(qyxx.getMonth() == null){
            qyxx.setMonth(DateUtilsEX.convertNumber2Chinese(cal.get(Calendar.MONTH)+1));
        }
        if(qyxx.getDay() == null){
            try {
                qyxx.setDay(DateUtilsEX.convertNumber2ChineseByDay(cal.get(Calendar.DATE)));
            } catch (Exception e) {
                log.error("企业资质设置时间-天错误"+e);
            }
        }
        if(StringUtils.isBlank(qyxx.getZsbh())){
            ywRqQyzzInfoQxService.createZsbh(form);
        }
        String tempPath="Templates/rqjyxk/qyzz.xls";
        logger.info("打印企业资质的文件路径"+tempPath);
       String context=getRequest().getSession().getServletContext().getRealPath("");
       tempPath=this.ywRqQyzzInfoQxService.writeZsData(form,qyxx,context);
       
       getRequest().setAttribute("templateFilePath",tempPath);
       logger.info("返回企业资质文件路径"+tempPath);
        return "printJyxkfbzs";
    }
	   /**
     * 套打资质证书
     * @return
	 * @throws IOException 
     */
    public String printSave() throws IOException{
         qyxx.setSqdw(form.getSqdw());
         String result="true";
        try {
        	form.setZsrq(new Date());//设置证书日期
            ywRqQyzzInfoQxService.save(form);
            ywComQyxxService.save(qyxx);
        } catch (Exception e) {
           log.error("打印保存出现错误"+e);
           result="false";
        }
        getResponse().getWriter().print(result);
        return null;
    }
	
    /**
     * 保存套打资质证书副本
     * @return
	 * @throws IOException 
     */
	public String printSavefb() throws IOException{
		this.ywComQyxxService.save(qyxx);
		this.ywRqQyzzInfoQxService.save(form);
        return this.preViewZzzsfb();
	}
	/**
	 * 套打资质证书副本
	 * @return
	 */
	public String preViewZzzsfb(){
		qyxx = ywComQyxxService.get(form.getQyid());
		//初始化打印时间
        Date da = new Date();
        Calendar cal = Calendar.getInstance();
        cal.setTime(da);
        if(qyxx.getYear() == null){
            qyxx.setYear(DateUtilsEX.convertNumber2Chinese(cal.get(Calendar.YEAR)));
        }
        if(qyxx.getMonth() == null){
            qyxx.setMonth(DateUtilsEX.convertNumber2Chinese(cal.get(Calendar.MONTH)+1));
        }
        if(qyxx.getDay() == null){
            qyxx.setDay(DateUtilsEX.convertNumber2ChineseByDay(cal.get(Calendar.DATE)));
        }
        String hjmc=getRequest().getParameter("hjmc");
        getRequest().setAttribute("hjmc", hjmc);
		return "preViewZzzsfb";
	}
	/**
	 * 套打资质证书副本
	 * @return
	 */
	public String printZzzsfb(){
		qyxx.setSqdw(form.getSqdw());
		ywRqQyzzInfoQxService.save(form);
		ywComQyxxService.save(qyxx);
		return "printZzzsfb";
	}
	
	
    /**
     * 出证
     */
    public String printcz() throws Exception {
    	form.setCbyw(form.getCbyw().replace("区县", "").replace("区", ""));
    	String taskId=getRequest().getParameter("taskInstDbid");
    	String activName="";
		if(StringUtils.isNotBlank(taskId)){
		  	WfBusInstanceTaskForm instance = wfService.getWfBusInstanceTaskById(Long.valueOf(taskId), this.getLoginUserName());
			activName=instance.getActivityName();
		    getRequest().setAttribute("activName", activName);
		}else{
			 getRequest().setAttribute("activName", "");
		}
		if(!"checkTable".equals(form.getFileCode())){//企业资质除了考核表，其他的文书都加载已经存在的
			if(form.getId() != null && form.getId() > 0){
	    		List<YwPrintDocForm> ywPrintDocFormList = ywPrintDocService.get(form.getTemplateCode(), form.getFileCode(), form.getId());
	        	if(ywPrintDocFormList!=null && ywPrintDocFormList.size()>0){
	    			return WfConstant.PRINT_DIR;
	    		}
	    	}
		}    	
        return WfUtilsEX.wfBusPrint(form,form.getId(),activName);
    }
    
    public String makeDocument() throws Exception {
    	String taskId=getRequest().getParameter("taskInstDbid");
    	String activName="";
		if(StringUtils.isNotBlank(taskId)){
		  	WfBusInstanceTaskForm instance = wfService.getWfBusInstanceTaskById(Long.valueOf(taskId), this.getLoginUserName());
			activName=instance.getActivityName();
		    getRequest().setAttribute("activName", activName);
		}else{
			 getRequest().setAttribute("activName", "");
		}
        if (StringUtils.isNotBlank(form.getRedHeadFileId())) {
            String redHeadFilePath = wfBusTemplateServiceEX.getPrintTemplatePath(Long.parseLong(form.getRedHeadFileId()));
            log.info("readheadFile----->"+redHeadFilePath);
            form.setRedHeadFilePath(redHeadFilePath);
        }
         //加载收件通知书里面的附件
		 String isred=getRequest().getParameter("isred");
		 //如果要打印红头
		 if("yes".equals(isred)){
			 String redHeadFilePath = wfBusTemplateServiceEX.getRedFile(form.getTemplateCode());
		      form.setRedHeadFilePath(redHeadFilePath);
		 }
        String templateCode = getTemplateCode();
        if(templateCode != null && templateCode.trim().length() > 0){
            String printTemplatePath = wfBusTemplateServiceEX.getPrintTemplatePath(templateCode, WfTemplateAttachmentRefFormEX.ZHENGWEN_TEMPLATE_TYPE);
            form.setTemplatePath(printTemplatePath);
            WfTemplateAttachmentRefFormEX wfTemplateAttachmentRefFormEX = 
            	(WfTemplateAttachmentRefFormEX)wfTemplateAttachmentRefServiceEX.get(Long.parseLong(form.getZhengwenFileId()));
            String zhengwenPath = wfTemplateAttachmentRefFormEX.getFilePath() + "/" + wfTemplateAttachmentRefFormEX.getFileRealName();
            form.setZhengwenPath(zhengwenPath);
            form.setCurDate(DateUtilsEX.convertDate2Chinese(new Date()));
            form.setCurYear(String.valueOf(Calendar.getInstance().get(Calendar.YEAR)));
            Long seq=oaDocCodeServiceEX.getQuCurSeqAndAddSeq(templateCode, wfTemplateAttachmentRefFormEX.getFileCode(),
            		form.getId(),this.getLoginUser());
             if(seq.intValue()<10){
	        	  form.setCurSeq("0"+String.valueOf(seq));
	        }else{
	        	  form.setCurSeq(String.valueOf(seq));
	        }
            WfUtilsEX.wfBusPrint(form,form.getId(),activName);
            BaseAction.getRequest().setAttribute("seq", form.getCurSeq());
            getRequest().setAttribute("isunified", false);//是否全委统一
            BaseAction.getRequest().setAttribute("templateFilePath",zhengwenPath);
            BaseAction.getRequest().setAttribute("fileCode", wfTemplateAttachmentRefFormEX.getFileCode());
            BaseAction.getRequest().setAttribute("entityId", form.getId());
            BaseAction.getRequest().setAttribute("templateId", wfTemplateAttachmentRefFormEX.getId());
//            BaseAction.getRequest().setAttribute("busType", OaFawen.class.getSimpleName());
        }
        return WfConstant.MAKE_DOCUMENT;
    }
    /**
     * 分页查询
     */
    @Override
    public String list() throws Exception {
        ywRqQyzzInfoQxService.search(page, form);
        return SUCCESS;
    }

    /**
     * 新增或修改
     */
    @Override
    public String input() throws Exception {
        //this.initWfOpinions();
        this.setOpinions();
        getRequest().setAttribute("CurrUserName", this.getLoginUser().getUser().getUserName());
        
        List<SysCodeForm> docTypeList = syscodeService.getItems("YW_QY_ZZDJ");
        List<SysCodeForm> zcjjxz = syscodeService.getItems("YW_ZCJJXZ");
        List<SysCodeForm> ywHbbm = syscodeService.getItems("ALL_HBBM");
        getRequest().setAttribute("qyzzdjList", docTypeList);
        getRequest().setAttribute("zcjjxzList", zcjjxz);
        getRequest().setAttribute("ywhbbmList", ywHbbm);
        
        return INPUT;
    }

    
    /**
     * 保存新增或者修改的Form对象
     */
    @Override
    public String save() throws Exception {
        ywRqQyzzInfoQxService.save(form);
        return RELOAD;
    }

    /**
     * 删除一条记录
     */
    @Override
    public String delete() throws Exception {
        ywRqQyzzInfoQxService.delete(form.getId());
        return RELOAD;
    }
    
    /**
     * 删除多条记录
     */
    @Override
    public String deleteMore() throws Exception{
        ywRqQyzzInfoQxService.delete(checkedIds);
        return RELOAD;
    }
    
    /**
     * 准备页面模型
     */
    @Override
    protected void prepareModel() throws Exception {
    	LoginUserForm uform=(LoginUserForm)BaseAction.getRequest().getSession().getAttribute("SES_LOGIN_USER");
		String username=uform.getUser().getUserName();

        String id = super.getParameter("id");
        if(StringUtils.isNotBlank(id)){
            form = ywRqQyzzInfoQxService.get(Long.parseLong(id));
        } else {
            form = new YwRqQyzzInfoForm();
        }
        if(StringUtils.isNotBlank(form.getCbyw())){
        	form.setCbyw(form.getCbyw().replace("区县", "").replace("区", ""));
        }        
        form.setCbyw2(form.getCbyw());
		form.setCbyw3(form.getCbyw());
		form.setCbyw4(form.getCbyw());
        if (StringUtils.isBlank(form.getAcceptNo())) {
        	String rq = DateUtilsEX.getYearAndMonthAndDay();
        	form.setAcceptNo("gz26"+rq+"XXXXX");
        }

        if (StringUtils.isBlank(form.getSjr())) {
            form.setSjr(this.getLoginUser().getUser().getUserName());
        }
        if (StringUtils.isBlank(form.getJbrxm())) {
            form.setJbrxm(this.getLoginUser().getUser().getUserName());
            form.setJbrxm2(this.getLoginUser().getUser().getUserName());
            form.setJbrdh(this.getLoginUser().getUser().getOfficeTel());
            form.setJbrdh2(this.getLoginUser().getUser().getOfficeTel());
        }
        form.setJbrdh2(form.getJbrdh());
        form.setSajg(uform.getOrg().getOrgName());
        form.setSajg2(form.getSajg());
        form.setSajg3(form.getSajg());
        form.setSajg4(form.getSajg());
        form.setSajg5(form.getSajg());
        form.setSajg6(form.getSajg());
        form.setQu("("+uform.getOrg().getOrgName().substring(0, 1)+")");
        if(StringUtils.isBlank(form.getJbrxm())){
            form.setJbrxm(this.getLoginUser().getUser().getUserName());
        }
        form.setJbrxm2(this.getLoginUser().getUser().getUserName());
    
        if(StringUtils.isBlank(form.getJbrdh())){
            form.setJbrxm(this.getLoginUser().getUser().getUserName());
        }
        if(StringUtils.isBlank(form.getJbrdh2())){
            form.setJbrxm2(this.getLoginUser().getUser().getUserName());
        }
        //if(form.getLarq() == null) 
        	form.setLarq(new Date());
        //if(form.getLarq2() == null)
        	form.setLarq2(new Date());
        
        if (StringUtils.isBlank(form.getCbyw())) {
            WfBusTemplateForm wfBusTemplateForm = wfBusTemplateServiceEX.getWfBusTemplateService().getByTemplateCode(getTemplateCode());
            if (wfBusTemplateForm != null) {
            	form.setCbyw(wfBusTemplateForm.getTemplateName().replace("区县", "").replace("区", ""));
            }
        }

        if (StringUtils.isBlank(form.getCbbm())) {
            form.setCbbm("燃气处");
        }

        if (form.getSarq() == null) {
            form.setSarq(new Date());
        }
        if (form.getCpsj() == null) {
            form.setCpsj(new Date());
        }
        if (form.getIeiDate() == null) {
            form.setIeiDate(new Date());
        }
        
        if(getTaskInstDbid() != null){
        	this.findJbrspUtil();	//获取审批过程中的意见列表
        	this.findCldspUtil();
        	this.findWldspUtil();
        	
        	this.cpbJbrspUtil();
        	this.cpbCldspUtil();
        	this.cpbWldspUtil();
        }
        
      //获取延期天数
    	int yqtsInt = wfServiceEX.getYqtsByProcInstId(super.getProcInstId());
    	form.setYqts(String.valueOf(yqtsInt));
    	//补交告知原因
    	if(form.getBjgzyy()==null){
    		form.setBjgzyy(this.getOpinion("jbrsl"));
    	}
    	//补交告知时间
    	if(form.getBjgzsj()==null){
    		form.setBjgzsj(new Date());
    	}
//    	//受理告知时间
//    	if(form.getBjslsj()==null){
//    		form.setBjslsj(new Date());
//    	}
    	//补交告知发出人
//    	if(form.getBjgzfcr()==null){
//    		form.setBjgzfcr(username);
//    	}
//        //补交告知受理人
//    	if(form.getSldwcbrxm()==null){
//    		form.setSldwcbrxm(username);
//    		
//    	}
    	//补交告知受理地点
    	if(form.getBjsljtdd()==null){
    		form.setBjsljtdd(uform.getOrg().getOrgName());
    	}
    	//答复时间
    	if(StringUtils.isNotBlank(id) && StringUtils.isNotBlank(this.getTemplateCode())){
    		Date date=this.wfServiceEX.getDfsjByTempleteCode(this.getTemplateCode(),Long.valueOf(id));
    		form.setDfsj(date);
    	}
    	
    	if(StringUtils.isNotBlank(this.getTemplateCode())){
    		form.setBranch(this.getTemplateCode());
    	}
    }
    
    /**
     * 获取企业主要设备与检测设备
     * @return
     * @throws IOException 
     */
    public String getEquipmentlist() throws IOException{
    	String qyid=getRequest().getParameter("qyid");
    	String acceptno=getRequest().getParameter("acceptNo");
    	 List<YwRqRyzzEquipment> list=ywRqQyzzEquipmentService.getQyzzEquipment(acceptno,Long.valueOf(qyid));
    	Gson gson=new Gson();
    	String result=gson.toJson(list).toString();
		HttpServletResponse response=getResponse();
		response.setCharacterEncoding("utf-8");
		response.getWriter().print(result);
    	return null;
    }
    /**
     * 获取单个企业主要设备与检测设备
     * @return
     * @throws IOException 
     */
    public String getEquipment() throws IOException{
    	String eid=getRequest().getParameter("eid");
    	 YwRqRyzzEquipment entity=ywRqQyzzInfoQxService.getEquipment(Long.valueOf(eid));
    	Gson gson=new Gson();
    	String result=gson.toJson(entity).toString();
		HttpServletResponse response=getResponse();
		response.setCharacterEncoding("utf-8");
		response.getWriter().print(result);
    	return null;
    }
    
    /**
     * 删除单个设备
     * @return
     * @throws IOException
     */
    public String delEquipment() throws IOException{
      	String eid=getRequest().getParameter("eid");
   	   ywRqQyzzInfoQxService.delEquipment(Long.valueOf(eid));
    	this.getEquipmentlist();
    	return null;
    }
    
    /**
     * 导出excel
     * @return
     * @throws Exception
     */
    public String exportInfo() throws Exception{
    	 String acceptNo=getRequest().getParameter("acceptNo");
         String username=getRequest().getParameter("username");
         String params=getRequest().getParameter("params");
         Long qyid=Long.valueOf(getRequest().getParameter("qyid"));
         String type=getRequest().getParameter("type");
         String contextpath=getSession().getServletContext().getRealPath("");
         String path= ywRqQyjyzzImportservice.exportExcel(qyid, acceptNo, username,params,contextpath,type);
           BufferedInputStream bis = null;
           OutputStream fos = null;
           InputStream fis = null;
           HttpServletResponse resp = null;
           HttpServletRequest request = null;
           String destUrl = path;
           try {
               resp = ServletActionContext.getResponse();
               request = ServletActionContext.getRequest();
               //设置字符编码格式
               resp.setCharacterEncoding("utf-8");
               try {
                request.setCharacterEncoding("utf-8");
               } catch (Exception e1) {
                e1.printStackTrace();
               } 
               File source = new File(destUrl);
               resp.setContentType("application/force-download");
               resp.setHeader("Content-Disposition", "attachment; filename=\""
                       + source.getName() + "\"");
               resp.setHeader("Pragma", "No-cache");
               resp.setHeader("Cache-Control", "no-cache");
               fos = resp.getOutputStream();
               bis = new BufferedInputStream(
                       new FileInputStream(source));
               byte[] content = new byte[5 * 1024];
               int length;
               while ((length = bis.read(content, 0, content.length)) != -1) {
                   fos.write(content, 0, length);
               }

               bis.close();
               fos.close();
               new File(path).delete();
           } catch (Exception e) {

               e.printStackTrace();
           } finally {
               if (fos != null) {
                   fos.close();
               }
               if (fis != null) {
                   fis.close();
               }
               if (bis != null) {
                   bis.close();
               }
           }
            return null;
    }
    
    /**
     * 获取其他信息，用于前台页面判断
     * @return
     * @throws IOException
     */
    public String getInfos() throws IOException{
    	String acceptNo=getRequest().getParameter("acceptNo");
    	String[] infos=ywRqQyzzInfoQxService.getInfos(acceptNo);
    	Map<String,String> map=new HashMap<String,String>();
    	map.put("sbInfo", infos[0]);
    	map.put("safetyPseron", infos[1]);
    	map.put("techPeson", infos[2]);
    	JSONObject json= JSONObject.fromObject(map); 
    	getResponse().getWriter().print(json.toString());
    	return null;
    }
    
    
    
    
    /**
	 * from加载	经办人审批意见列表工具方法
	 */
	private void findJbrspUtil(){
		String names = "'jbrsl' , 'jbrsj'";
		List<Jbpm4HistTask> list = wfServiceEX.getHandleCommentsByTaskInstDbidAndActivityNames(getTaskInstDbid(),names);
		StringBuffer jbrspYj = new StringBuffer();
		for(int i=list.size()-1;i>=0;i--){//只取一条记录
			if(StringUtils.isNotBlank(list.get(i).getHandleComments())){
				jbrspYj.append(list.get(i).getHandleComments());
				form.setJbrslsj(list.get(i).getHandleCommentsTime());
				form.setJbrslxm(list.get(i).getAssigneeName());
				break;
			}
		}
		form.setJbrsl(jbrspYj.toString());
	}
	/**
	 * from加载	处领导审批意见列表工具方法
	 */
	private void findCldspUtil(){
		String names = "'cfgldsh' , 'czgldsh'";
		List<Jbpm4HistTask> list = wfServiceEX.getHandleCommentsByTaskInstDbidAndActivityNames(getTaskInstDbid(),names);
		StringBuffer cldspYj = new StringBuffer();
		for(int i=list.size()-1;i>=0;i--){
			if(StringUtils.isNotBlank(list.get(i).getHandleComments())){
				cldspYj.append(list.get(i).getHandleComments());
				form.setJbrslsj(list.get(i).getHandleCommentsTime());
				form.setJbrslxm(list.get(i).getAssigneeName());
				break;
			}
		}
		form.setCldsp(cldspYj.toString());
	}
	/**
	 * from加载	委领导审批意见列表工具方法
	 */
	private void findWldspUtil(){
		String names = "'wfgldsh' , 'wzgldsp'";
		List<Jbpm4HistTask> list = wfServiceEX.getHandleCommentsByTaskInstDbidAndActivityNames(getTaskInstDbid(),names);
		StringBuffer wldspYj = new StringBuffer();
		for(int i=list.size()-1;i>=0;i--){
			if(StringUtils.isNotBlank(list.get(i).getHandleComments())){
				wldspYj.append(list.get(i).getHandleComments());
				form.setWldspsj(list.get(i).getHandleCommentsTime());
				form.setWldspxm(list.get(i).getAssigneeName());
				break;
			}
		}
		form.setWldsp(wldspYj.toString());
	}
	//打印 呈批表经办人意见
	private void cpbJbrspUtil(){
		String names = "'jbrsl' , 'jbrsj'";
		List<Jbpm4HistTask> list = wfServiceEX.getHandleCommentsByTaskInstDbidAndActivityNames(getTaskInstDbid(),names);
		StringBuffer jbrspYj = new StringBuffer();
		for(int i=list.size()-1;i>=0;i--){
		  if(StringUtils.isNotBlank(list.get(i).getHandleComments())){
			jbrspYj.append(list.get(i).getHandleComments()).append("\n")
			.append("    ").append(list.get(i).getAssigneeName()).append("\n")
			.append(simpleDateFormat.format(list.get(i).getHandleCommentsTime())).append("\n");
			break;
		 }
		}
		form.setCpbJbryj(jbrspYj.toString());
	}
	//打印  呈批表 处领导意见
	private void cpbCldspUtil(){
		String names = "'cfgldsh' , 'czgldsh'";
		List<Jbpm4HistTask> list = wfServiceEX.getHandleCommentsByTaskInstDbidAndActivityNames(getTaskInstDbid(),names);
		StringBuffer cldspYj = new StringBuffer();
		for(int i=list.size()-1;i>=0;i--){
			try {
				if(StringUtils.isNotBlank(list.get(i).getHandleComments())){
					cldspYj.append(list.get(i).getHandleComments()).append("\n")
					.append("    ").append(list.get(i).getAssigneeName()).append("\n")
					.append(simpleDateFormat.format(list.get(i).getHandleCommentsTime())).append("\n");
					break;
				}
			} catch (RuntimeException e) {
				log.error("呈批表意见的时间出现错误"+e);
				e.printStackTrace();
			}
		}
		form.setCpbCldyj(cldspYj.toString());
	}
	//打印  呈批表 委领导意见
	private void cpbWldspUtil(){
		String names = "'wfgldsh' , 'wzgldsp'";
		List<Jbpm4HistTask> list = wfServiceEX.getHandleCommentsByTaskInstDbidAndActivityNames(getTaskInstDbid(),names);
		StringBuffer wldspYj = new StringBuffer();
		for(int i=list.size()-1;i>=0;i--){
			if(StringUtils.isNotBlank(list.get(i).getHandleComments())){
				wldspYj.append(list.get(i).getHandleComments()).append("\n")
				.append("    ").append(list.get(i).getAssigneeName()).append("\n")
				.append(simpleDateFormat.format(list.get(i).getHandleCommentsTime())).append("\n");
				break;
			}
		}
		form.setCpbWldyj(wldspYj.toString());
	}
    public YwRqQyzzInfoForm getModel() {
        return form;
    }
    
    /**
     * 经办人结案的时候检查数据后上传文件
     * @return
     * @throws Exception
     */
    public String importReUpload() throws Exception{
        Map map=getMapByRequest(getRequest());
        ywRqQyjyzzImportservice.reImportExcel(map);
        
        return null;
    }
    
    public String   checkImportData() throws Exception{
        String result="";
        Map map=getMapByRequest(getRequest());
        String qyid=(String) map.get("qyid");
        YwComFinalQyxx finalQyxx=ywRqQyzzInfoQxService.getYwComFinalQyxx(Long.valueOf(qyid));
        if(finalQyxx!=null){
        }else{
            String contextPath=getRequest().getSession().getServletContext().getRealPath("");
            map.put("contextPath", contextPath);
        	result=ywRqQyjyzzImportservice.checkImportPerson(map);
            //result="notexist";
        }
        getResponse().getWriter().print(result);
        return null;
    }
    
    
    /**
     * 窗口收案环节导入数据
     */
    public String  importFinalData() throws Exception{
        Map map=getMapByRequest(getRequest());
        map.put("templateCode", form.getTemplateCode());
        String contextPath=getRequest().getSession().getServletContext().getRealPath("");
        map.put("contextPath", contextPath);
        String result=ywRqQyjyzzImportservice.importFinalData(map);
        getResponse().getWriter().print(result);
        return null;
    }
    
    /**
     * 进入导入正式企业信息页面
     * @return
     * @author @zhangjun
     * @date 2011-10-16
     */
    public String showview(){
        getRequest().setAttribute("CurrUserName", this.getLoginUser().getUser().getUserName());
        if(form!=null){
            //最终企业表
           YwComFinalQyxx finalEntity=this.ywRqQyzzInfoQxService.getYwComFinalQyxx(form.getQyid());
           //安全技术人员
           List<YwRqQyzzJsRy>  ayjsRys=this.ywRqQyzzInfoQxService.getJsRys(form.getQyid(),form.getAcceptNo());
           List<YwRqQyzzFinalJsRy> finalayjsRys=this.ywRqQyzzInfoQxService.getFinalJsRys(form.getQyid());
           //安装维修人员
           List<YwRqQyzzAzWxRyZs> azwxrys=this.ywRqQyzzInfoQxService.getAzWxRys(form.getQyid(),form.getAcceptNo());
           List<YwRqQyzzFinalAzWxRyZs> finalazwxrys=this.ywRqQyzzInfoQxService.getFinalAzWxRys(form.getQyid());
           //主要设备
           List<YwRqRyzzFinalEquipment> finalEquipments=this.ywRqQyzzInfoQxService.getFinalEquipments(form.getQyid());
           List<YwRqRyzzEquipment> euipments=this.ywRqQyzzInfoQxService.getEquipments(form.getQyid(),form.getAcceptNo());
           //其他材料
           List<YwRqRyzzFinalOtherEvidence> finalOtherEvidences=this.ywRqQyzzInfoQxService.getFinalOtherEvidences(form.getQyid());
           List<YwRqRyzzOtherEvidence> otherEvidences=this.ywRqQyzzInfoQxService.getOtherEvidences(form.getQyid(),form.getAcceptNo());
           //最终企业表
           getRequest().setAttribute("finalEntity",finalEntity);
           //安全技术人员
           getRequest().setAttribute("ayjsRys",ayjsRys);
           getRequest().setAttribute("finalayjsRys",finalayjsRys);
           //安装维修人员
           getRequest().setAttribute("azwxrys",azwxrys);
           getRequest().setAttribute("finalazwxrys",finalazwxrys);
           //主要设备
           getRequest().setAttribute("euipments",euipments);
           getRequest().setAttribute("finalEquipments",finalEquipments);
           //其他材料
           getRequest().setAttribute("otherEvidences",otherEvidences);
           getRequest().setAttribute("finalOtherEvidences",finalOtherEvidences);
           
        }
        return "showview";
    }
    
    /**
     * 最后环节导入数据
     * @return
     * @throws Exception
     */
   public String  importFinalQyData() throws Exception{
      Map map=ywRqQyjyzzImportservice.importFinalQyData(form);
       
       return null;
   }
    

    /**
     * 修改企业信息
     * @return
     * @throws Exception
     */
    public String doUpdate() throws Exception{
        Enumeration enu = getRequest().getParameterNames();
        String jsonStr="";
        while(enu.hasMoreElements()) {   
            String paraName = (String)enu.nextElement();   
            if(StringUtils.isNotBlank(paraName)){        
                jsonStr=paraName;
            }
        }  
        JSONObject jsonObject = JSONObject.fromObject(jsonStr); 
        YwRqQyzzInfoForm entity=(YwRqQyzzInfoForm) JSONObject.toBean(jsonObject, YwRqQyzzInfoForm.class);
        try {
            this.ywRqQyzzInfoQxService.save(entity);
            getResponse().getWriter().print("success");
        } catch (Exception e) {
            log.error("修改失败"+e);
            getResponse().getWriter().print("fail");
        }
        
         return null;
   }
    
    
    
    /**
     * 查看正式企业信息前检查数据
     * @return
     * @throws Exception
     */
    public String checkViewData() throws Exception{
        String qyid=getRequest().getParameter("qyid");
        YwComFinalQyxx finalQyxx=ywRqQyzzInfoQxService.getYwComFinalQyxx(Long.valueOf(qyid));
        if(finalQyxx==null){
           getResponse().getWriter().print("dataNotExist");
        }
        
        return null;
    }
    
    /**
     *获取返回后导入的数据
     * @return
     * @throws IOException 
     */
    public String getResultImportData () throws IOException{
       if(form!=null && form.getId()!=null){
           JSONObject jsonObject = JSONObject.fromObject(form); 
           getResponse().getWriter().print(jsonObject.toString());
       }
        return null;
    }
    
    
    
    
  //获取request对象中所有参数，并设置到map中
    private  Map getMapByRequest(HttpServletRequest request) {
        Map<String, String> map = new HashMap<String, String>();
        Enumeration enu = request.getParameterNames();
        while(enu.hasMoreElements()) {   
            String paraName = (String)enu.nextElement();   
            String paraValue = request.getParameter(paraName).trim(); 
            if(paraValue!=null && !"".equals(paraValue)){
                map.put(paraName, paraValue);
            }           
        }
                
        return map;
    }
    
    
    
    // 属性getter和setter方法
    public Long[] getCheckedIds() {
        return checkedIds;
    }

    public void setCheckedIds(Long[] checkedIds) {
        this.checkedIds = checkedIds;
    }
    
    public Page<YwRqQyzzInfoForm> getPage() {
        return page;
    }


    public void setPage(Page<YwRqQyzzInfoForm> page) {
        this.page = page;
    }
	public YwComQyxxForm getQyxx() {
		return qyxx;
	}
	public void setQyxx(YwComQyxxForm qyxx) {
		this.qyxx = qyxx;
	}
    
}
